package com.project.util;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;
import java.util.UUID;

public class QiniuCloudUtil {
      private static final String QiniuCloud_accessKey = "HUsgK1BeV4jncLUNiuL4uwfSNn26N1q-baB0W5Go";
      
      private static final String QiniuCloud_secretKey = "T6JNldHt_j_HU5sD7wM5F21asiYxdztdwwdgA7Y1";
      
      private static final String QiniuCloud_bucket = "vvzs";
      
      private static final String QiniuCloud_domainName = "http://ru8jo0hyz.hd-bkt.clouddn.com/";
      
      private static final String customSuffix = ".png";//定义图片保存后的后缀
      /**
       * 上传图片到七牛云
       * @param file 图片
       * @return 返回图片存储后的新图片名
       * @throws Exception
       */
      public static Object QiniuCloudUploadImage(MultipartFile file) throws Exception{
            if(file.isEmpty()) {
                  return "文件为空";
            }else if(file.getSize() > 1024*1024*10){
                  return "文件大于10M";
            }
            //获取图片后缀
            String originalFilename = file.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            //允许上传的图片格式集合
            String[] suffixes = new String[]{".bmp", ".jpeg", ".jpg", ".png"};
            boolean bool = false;
            //判断格式是否在suffixes中
            for(String string : suffixes){
                  if (string.equals(suffix)){
                        bool = true;
                        break;
                  }
            }
            if(!bool){
                  return "图片格式错误";
            }
            //构造一个带指定 Region 对象的配置类
            Configuration cfg = new Configuration(Region.autoRegion());
            cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;//指定分片上传版本
            UploadManager uploadManager = new UploadManager(cfg);
            //生成上传凭证，然后准备上传
            String accessKey = QiniuCloud_accessKey;
            String secretKey = QiniuCloud_secretKey;
            String bucket = QiniuCloud_bucket;
            //默认不指定key的情况下，以文件内容的hash值作为文件名
            String key = UUID.randomUUID().toString().replaceAll("-", "") + customSuffix;//生成新的文件名
            
            try {
                  byte[] uploadBytes = file.getBytes();
                  ByteArrayInputStream byteInputStream=new ByteArrayInputStream(uploadBytes);
                  Auth auth = Auth.create(accessKey, secretKey);
                  String upToken = auth.uploadToken(bucket);
                  
                  try {
                        uploadManager.put(byteInputStream,key,upToken,null, null);
                  } catch (QiniuException ex) {
                        Response r = ex.response;
                        System.err.println("七牛云ERROR:" + r.toString());
                        try {
                              System.err.println("七牛云ERROR:" + r.bodyString());
                        } catch (QiniuException ex2) {
                              //ignore
                        }
                  }
            } catch (UnsupportedEncodingException ex) {
                  //ignore
            }
            
            return key;
      }
      /**
       * 获取七牛云图片链接
       * @param fileName 图片名
       * @return 返回图片链接
       */
      public static Object QiniuCloudDownloadImage(String fileName){
            String fileUrl = String.format("%s/%s", QiniuCloud_domainName, fileName);
            return fileUrl;
      }



}
